package com.example.wisdombookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.wisdombookstore.entity.*;

import com.example.wisdombookstore.mapper.*;
import com.example.wisdombookstore.service.IClerkService;
import com.example.wisdombookstore.util.IdWorker;
import com.example.wisdombookstore.util.ResponseResult;
import com.example.wisdombookstore.util.StateConstant;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName ClerkServiceImpl
 * @Description TODO 8aceMak1r ClerkServiceImpl 工作人员接口
 * @Author 8aceMak1r
 * @Date 2020/10/22 14:47
 * @Version 1.0
 */
@Service
@Slf4j
public class ClerkServiceImpl extends ServiceImpl<TbClerkMapper, TbClerk> implements IClerkService {
    /**
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger(ClerkServiceImpl.class);

    @Autowired
    private TbClerkMapper clerkMapper;

    @Autowired
    private IdWorker idWorker;

    @Override
    public ResponseResult clerkLogin(TbClerk clerk, HttpSession session) {
        log.info(clerk.toString());
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>(16);
        QueryWrapper<TbClerk> wrapper = new QueryWrapper<>();
        String md5Password = DigestUtils.md5DigestAsHex(clerk.getPassword().getBytes());
        wrapper.lambda().eq(TbClerk::getMobile, clerk.getMobile()).eq(TbClerk::getPassword, md5Password);
        TbClerk clerk1 = clerkMapper.selectOne(wrapper);
        if (clerk1 == null) {
            result.setFailMessage("账号或密码错误");
            return result;
        }
        if (clerk1.getStatus().equals(StateConstant.TBUSER_STATE_LOCKING)) {
            result.setFailMessage("用户已离职");
            return result;
        }
        //判断权限
        if (clerk1.getPermissions().equals(StateConstant.TBCLERK_PERMISSIONS_STOREMANAGER)) {
            //登录的用户名和角色存入session
            session.setAttribute("username", clerk1.getName());
            session.setAttribute("permissions", clerk1.getPermissions());
            resultMap.put("clerk", clerk1);
            resultMap.put("username", session.getAttribute("username"));
            resultMap.put("permissions", session.getAttribute("permissions"));
            result.setResult(resultMap);
            result.setMessage("店长登录成功");

            return result;
        }
        //登录的用户名和角色存入session
        session.setAttribute("username", clerk1.getName());
        session.setAttribute("permissions", clerk1.getPermissions());
        resultMap.put("clerk", clerk1);
        resultMap.put("username", session.getAttribute("username"));
        resultMap.put("permissions", session.getAttribute("permissions"));
        result.setResult(resultMap);
        result.setMessage("工作人员登录成功");
        return result;
    }

    @Override
    public ResponseResult clerkLogout(HttpServletRequest request) {
        ResponseResult result = ResponseResult.SUCCESS();
        //注销删除session
        request.getSession().removeAttribute("username");
        request.getSession().removeAttribute("permissions");
        request.getSession().invalidate();
        result.setMessage("退出成功");
        result.setSuccess(true);
        result.setCode(1);
        return result;
    }


    @Override
    public ResponseResult addClerk(TbClerk clerk) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap(16);
        try {
            TbClerk clerk1 = clerkMapper.selectOne(new QueryWrapper<TbClerk>().eq("mobile", clerk.getMobile()).last("limit 1"));
            TbClerk clerk2 = new TbClerk();
            if (clerk1 != null) {
                result.setFailMessage("手机号已存在");
                return result;
            } else {
                clerk2.setName(clerk.getName());
                clerk2.setMobile(clerk.getMobile());
                clerk2.setCreateTime(clerk.getCreateTime());
                clerk2.setUpdateTime(clerk.getCreateTime());
                clerk2.setAge(clerk.getAge());
                clerk2.setAddress(clerk.getAddress());
                clerk2.setIdCard(clerk.getIdCard());
                clerk2.setBootStoreCode(clerk.getBootStoreCode());
                clerk2.setStatus(clerk.getStatus());
                clerk2.setPermissions(clerk.getPermissions());
                clerk2.setCode(idWorker.nextId());
                //md5密码加密
                String md5Password = DigestUtils.md5DigestAsHex(clerk.getPassword().getBytes());
                logger.info("pass:" + md5Password);
                clerk2.setPassword(md5Password);
                clerkMapper.insert(clerk2);
                if (clerk2 != null) {
                    //密码不展示
                    clerk2.setPassword("");
                    resultMap.put("clerk", clerk2);
                    result.setSuccess(true);
                    result.setMessage("添加成功");
                    result.setCode(1);
                    result.setResult(resultMap);
                    logger.info("添加成功:" + clerk2);
                    return result;
                } else {
                    logger.info("添加失败");
                    result.setFailMessage("添加失败");
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("程序异常" + e.toString());
            result.setSuccess(false);
            return result;
        }
    }

    @Override
    public ResponseResult getClerkList(Integer pageSize, Integer pageCurrent) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            Page<TbClerk> page = new Page<TbClerk>(pageCurrent, pageSize);
            Page<TbClerk> clerkPage = clerkMapper.selectPage(page, new QueryWrapper<TbClerk>().eq("is_del", StateConstant.OBJECT_DEL_NORMAL));
            HashMap<String, Object> hashMap = new HashMap<>(10);
            hashMap.put("pages", clerkPage);
            result.setResult(hashMap);
            logger.info("查询成功" + hashMap);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setFailMessage("程序异常" + e.toString());
            return result;
        }
    }

    @Override
    public ResponseResult getClerkById(Long tbUserId) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>(16);
        try {
            QueryWrapper<TbClerk> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(TbClerk::getCode, tbUserId);
            TbClerk clerk = clerkMapper.selectOne(wrapper);
            if (clerk == null) {
                logger.info("用户不存在");
                result.setFailMessage("用户不存在");
                return result;
            } else {
                resultMap.put("clerk", clerk);
                result.setResult(resultMap);
                logger.info("查询成功:" + resultMap.toString());
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setFailMessage("程序异常" + e.toString());
            return result;
        }
    }

    @Override
    public ResponseResult setClerkById(TbClerk clerk) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap(16);
        try {
            TbClerk clerk1 = clerkMapper.selectOne(new QueryWrapper<TbClerk>().eq("code", clerk.getCode()).last("limit 1"));
            TbClerk clerk2 = new TbClerk();
            if (clerk1 == null) {
                result.setFailMessage("用户不存在");
                return result;
            } else {
                clerk2.setName(clerk.getName());
                clerk2.setMobile(clerk.getMobile());
                clerk2.setUpdateTime(new Date());
                clerk2.setStatus(clerk.getStatus());
                clerk2.setCode(clerk.getCode());
                clerk2.setPermissions(clerk.getPermissions());
                clerkMapper.update(clerk2, new QueryWrapper<TbClerk>().eq("code", clerk2.getCode()));
                if (clerk2 != null) {
                    resultMap.put("clerk", clerk2);
                    result.setSuccess(true);
                    result.setMessage("修改成功");
                    result.setCode(1);
                    result.setResult(resultMap);
                    logger.info("修改成功:" + clerk2);
                    return result;
                } else {
                    logger.info("修改失败");
                    result.setFailMessage("修改失败");
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("程序异常" + e.toString());
            result.setSuccess(false);
            return result;
        }
    }

    @Override
    public ResponseResult setClerkPassword(Long tbUserId, String oldPassword, String newPassword) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>(10);
        String oldMd5Password = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        try {
            QueryWrapper<TbClerk> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(TbClerk::getCode, tbUserId);
            TbClerk clerk = clerkMapper.selectOne(wrapper);
            if (clerk == null) {
                result.setFailMessage("用户名不存在");
                logger.info("操作失败" + result.toString());
                return result;
            } else if (!clerk.getPassword().equals(oldMd5Password)) {
                result.setFailMessage("原密码错误");
                logger.info("操作失败:" + result.toString());
                return result;
            } else {
                String newMd5Password = DigestUtils.md5DigestAsHex(newPassword.getBytes());
                clerk.setPassword(newMd5Password);
                clerkMapper.update(clerk, new QueryWrapper<TbClerk>().eq("code", tbUserId));
                resultMap.put("clerk", clerk);
                result.setResult(resultMap);
                result.setSuccess(true);
                result.setMessage("操作成功");
                logger.info("操作成功:" + result.toString());
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("程序异常" + e.toString());
            result.setSuccess(false);
            return result;
        }
    }

    @Override
    public ResponseResult delClerkById(Long tbUserId) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>(16);
        try {
            QueryWrapper<TbClerk> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(TbClerk::getCode, tbUserId);
            TbClerk clerk = clerkMapper.selectOne(wrapper);
            if (clerk == null) {
                result.setFailMessage("用户不存在");
                logger.info("操作失败:" + result.toString());
                return result;
            } else {
                clerk.setStatus(StateConstant.TBUSER_STATE_LOCKING);
                clerkMapper.update(clerk, new QueryWrapper<TbClerk>().eq("code", tbUserId));
                resultMap.put("clerk", clerk);
                result.setMessage("操作成功");
                result.setSuccess(true);
                result.setCode(1);
                logger.info("操作成功:" + result.toString());
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("程序异常" + e.toString());
            result.setSuccess(false);
            return result;
        }
    }

    @Override
    public ResponseResult clerkList(int page,int size) {
        ResponseResult result=ResponseResult.SUCCESS();
        Page<TbClerk> objectPage = new Page<>(page, size);
        HashMap<String, Object> resultMap=new HashMap<>();
        try {
            Page<TbClerk> tbClerkPage = clerkMapper.selectPage(objectPage, new QueryWrapper<TbClerk>());
            if (tbClerkPage.getTotal()==0){
                result.setFailMessage("查询失败");
                return result;
            }else{
                resultMap.put("clerk",tbClerkPage.getRecords());
                resultMap.put("tokal",tbClerkPage.getTotal());
                result.setResult(resultMap);
                result.setSuccess(true);
                result.setMessage("操作成功");
                return result;
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMessage("程序异常" + e.toString());
            result.setSuccess(false);
            return result;
        }
    }

    @Override
    public ResponseResult clerkList() {
        ResponseResult result=ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap=new HashMap<>();
        try {
            List<TbClerk> tbClerks = clerkMapper.selectList(new QueryWrapper<TbClerk>());
            if (tbClerks==null){
                result.setFailMessage("查询失败");
                return result;
            }else{
                resultMap.put("tbClerks",tbClerks);
                result.setResult(resultMap);
                result.setSuccess(true);
                result.setMessage("操作成功");
                return result;
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMessage("程序异常" + e.toString());
            result.setSuccess(false);
            return result;
        }
    }


}
